<template>
  <el-dialog v-if="visible" title="导出" :visible.sync="visible" append-to-body width="555px" :show-close="false">
    <avue-form ref="form" v-model="form" :option="localOption">
      <template slot-scope="{ row }" slot="type">
        <el-radio-group v-model="form.type">
          <el-radio label="current" class="custom-radio">当前页面数据</el-radio>
          <el-radio label="all" class="custom-radio">全部数据</el-radio>
        </el-radio-group>
      </template>
    </avue-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleExport" size="small">导出</el-button>
      <el-button size="small" @click="handleClose">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { Message } from 'element-ui';
import request from '@/router/axios';
import { calcCascader, loadCascaderDic, loadDic } from '@/components/export-excel/util';

export default {
  name: 'exportComp',
  props: {
    option: {
      type: Object,
      default: () => ({})
    },
    query: {
      type: Object,
      default: () => ({})
    },
    page: {
      type: Object,
      default: () => ({})
    },
    fileName: {
      type: String,
      default: ''
    },
    reportCode: {
      type: String,
      default: ''
    },
    pageApiUrl: {
      type: String,
      default: ''
    },
    pageApiMethod: {
      type: String,
      default: ''
    },
    exclude: {
      type: Array,
      default: []
    },
    dataListChain: {
      // 代表 分页接口返回数据data与records之间的对象层级
      // ，如：data.dataSub.dataList.records, 需要传入`dataSub.dataList`。可以为空）
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      maxPageSize: 10,
      exportUrl: '/api/mes-admin/excelExport/export',
      cascaderDIC: {},
      DIC: {},
      localOption: {
        row: true,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '文件名',
            prop: 'name',
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入文件名',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '选择数据',
            prop: 'type',
            type: 'radio',
            value: 'current',
            span: 24
          },
          {
            label: '选择字段',
            prop: 'prop',
            type: 'tree',
            multiple: true,
            tags: false,
            checkStrictly: false,
            checkOnClickNode: true,
            span: 24,
            props: {
              value: 'prop'
            },
            dicData: []
          },
          {
            label: '参数设置',
            prop: 'params',
            type: 'checkbox',
            span: 24,
            dicData: [
              {
                label: '表头',
                disabled: true,
                value: 'header'
              },
              {
                label: '数据源',
                disabled: true,
                value: 'data'
              }
              // {
              //   label: '复杂表头',
              //   value: ''
              // },
              // {
              //   label: '合计统计',
              //   value: ''
              // }
            ],
            value: ['header', 'data']
          }
        ]
      },
      columnOption: [],
      form: {
        name: this.fileName,
        type: 'current'
      }
    };
  },
  computed: {
    propOption() {
      let result = [];
      function findProp(list = []) {
        if (!Array.isArray(list)) return;
        list.forEach((ele) => {
          if (Array.isArray(ele.children)) findProp(ele.children);
          else result.push(ele);
        });
      }
      findProp(this.columnOption);
      result = calcCascader(result);
      return result;
    },
    resultOption() {
      return Object.assign(this._cloneDeep(this.option), {
        column: this.propOption
      });
    }
  },
  async mounted() {
    this.getColumnOption();
    await this.dicInit();
  },
  watch: {
    fileName(val) {
      if (val) {
        this.form.name = val;
      }
    },
    option: {
      handler(val) {
        this.getColumnOption();
      },
      deep: true
    }
  },
  methods: {
    async dicInit(type) {
      if (type === 'cascader') {
        await this.handleLoadCascaderDic();
      } else {
        await this.handleLoadDic();
      }
    },
    handleExport() {
      try {
        this.getExportExcelBody();
        //  this.globalStartLoad('数据导出中，请稍后...');
        request({
          url: this.exportUrl,
          method: 'POST',
          params: this.getParams(),
          data: this.getExportExcelBody()
        })
          .then((res) => {
            this.$emit('success', true);
            this.$message.success(res.data.msg);
            this.$emit('success', true);
          })
          .catch((e) => {
            this.$message.error('系统错误,请联系管理员!');
          });
      } catch (e) {
        Message({
          message: '请联系管理员',
          type: 'error'
        });
        console.log(e);
      }
      this.handleClose();
    },
    getParams() {
      const params = {
        ...this.query
      };
      if (this.form.type === 'all' || !Object.keys(this.page).length) {
        params.isExportAll = true;
      } else {
        params.size = this.page.pageSize;
        params.current = this.page.currentPage;
      }
      return params;
    },
    getExportExcelBody() {
      const customColumns = {};
      const dictColumns = [];
      let columns = this.getColumn();
      for (let i = 0; i < columns.length; i++) {
        const dictObj = {};
        // 导出的列名
        customColumns[columns[i].prop] = columns[i].label;
        // 拼接接口数据源参数
        if (columns[i].prop in this.DIC && !this.exclude.includes(columns[i].prop)) {
          const prop = columns[i].prop;
          const dictKey = columns[i].props.value;
          const dicLabel = columns[i].props.label;
          const dic = this._cloneDeep(this.DIC);
          const data = dic[prop].map((item) => {
            return { label: item[dicLabel], value: item[dictKey] };
          });
          dictColumns.push({
            prop: columns[i].prop,
            boolType: false,
            dictList: data
          });
        }
        // 表格中需要转换数据
        if (columns[i].dicData && columns[i].dicData.length) {
          dictColumns.push({
            prop: columns[i].prop,
            boolType: false,
            dictList: columns[i].dicData
          });
        }
      }
      const body = {
        fileName: this.form.name || this.fileName,
        pageApiUrl: this.pageApiUrl,
        customColumns,
        dictColumns,
        reportCode: this.reportCode
      };
      if (this.reportCode) {
        body.reportCode = this.reportCode;
      }
      if (this.pageApiMethod === 'POST') {
        body.pageApiMethod = this.pageApiMethod;
      }
      if (this.dataListChain) {
        body.dataListChain = this.dataListChain;
      }
      return body;
    },
    handleClose() {
      this.form.type = 'current';
      this.visible = false;
    },
    getColumnOption() {
      let column = this._cloneDeep(this.option).column || [];
      let prop = [];
      const findProp = (list = []) => {
        list.forEach((ele, index) => {
          let children = ele.children;
          if (children && !Array.isArray(children)) delete ele.children;
          else if (ele.showColumn === false) list.splice(index, 1);
          else {
            if (!ele.hideProp) {
              prop.push(ele.prop);
            }
            if (ele.children) findProp(children);
          }
        });
      };
      const dicProp = this.findObject(this.localOption.column, 'prop');
      dicProp.dicData =
        this._cloneDeep(this.option).column.filter((item) => {
          item.disabled = false;
          return !item.hide;
        }) || [];
      findProp(column);
      this.columnOption = column;
      this.$set(this.form, 'prop', prop);
    },
    // 获取导出的列
    getColumn() {
      let columns = this._cloneDeep(this.columnOption);
      let props = this.$refs.form.getPropRef('prop').$refs.temp.getHalfList();
      let result = [];
      const findProp = (list = []) => {
        list.forEach((ele, index) => {
          if (ele.children) {
            findProp(ele.children);
          } else if (props.includes(ele.prop)) {
            result.push(ele);
          }
        });
      };
      findProp(columns);
      return result.filter((item) => !item.hide);
    },
    // 网络字典加载
    handleLoadDic() {
      loadDic(this.resultOption, this);
    },
    //级联字典加载
    handleLoadCascaderDic() {
      loadCascaderDic(this.propOption, this);
    }
  }
};
</script>
<style lang="scss">
.custom-radio {
  width: 100%;
  height: 40px;
  line-height: 30px;
}
.pages-select {
  display: inline-block;
  .number-input {
    width: 100px;
  }
}
</style>
